<template>
  <div class="status-distribution-container">
    <h2>资产状态分布</h2>
    
    <div class="filter-bar">
      <el-select v-model="statusFilter" placeholder="选择状态" @change="handleFilterChange">
        <el-option label="全部状态" value="" />
        <el-option label="在用" value="在用" />
        <el-option label="闲置" value="闲置" />
        <el-option label="维修" value="维修" />
        <el-option label="报废" value="报废" />
        <el-option label="借用" value="借用" />
      </el-select>
      <el-select v-model="categoryFilter" placeholder="选择分类" @change="handleFilterChange">
        <el-option label="全部分类" value="" />
        <el-option label="电子设备" value="电子设备" />
        <el-option label="办公家具" value="办公家具" />
        <el-option label="车辆设备" value="车辆设备" />
        <el-option label="生产设备" value="生产设备" />
        <el-option label="其他" value="其他" />
      </el-select>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>
    
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产状态饼图</span>
          </div>
        </template>
        <div id="statusPieChart" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产状态柱状图</span>
          </div>
        </template>
        <div id="statusBarChart" class="chart"></div>
      </el-card>
    </div>
    
    <div class="data-table">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>状态明细数据</span>
          </div>
        </template>
        <el-table :data="statusDetails" style="width: 100%">
          <el-table-column prop="status" label="资产状态" />
          <el-table-column prop="count" label="数量" />
          <el-table-column prop="percentage" label="占比" />
          <el-table-column prop="totalValue" label="总价值" formatter="formatMoney" />
          <el-table-column prop="avgValue" label="平均价值" formatter="formatMoney" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { getAssetStatusDistributionAPI } from '@/api/asset.js'
import { formatter } from 'element-plus'


// 响应式数据
const statusFilter = ref('')
const categoryFilter = ref('')
const statusDetails = ref([])
//两个图像
const pieChart = ref(null)
const barChart = ref(null)
//两个图像的数据
let assetList = [] 

// 加载数据
const loadData = async () => {
  try{
    const res = await getAssetStatusDistributionAPI()
    console.log("res是", res)
    if(res.status == 200){
      assetList = res.data.data
      console.log("asset是",assetList)
      initStatusPieChart(assetList)//传入全量数据统计状态分布
      initStatusBarChart(assetList)//传入到树状图中
    }else{
       // 无数据时重置
      initCharts()
      ElMessage.warning('暂无资产数据')
    }
  }catch(error){
    initCharts()
    ElMessage.error('数据加载失败，请重试')
  }
}
// 初始化饼图
const initStatusPieChart = (assetList) => {
  const chartDom = document.getElementById('statusPieChart')
  if (!chartDom) return

    // 销毁旧实例，避免内存泄漏
  if (statusPieChart.value) {
    statusPieChart.value.dispose()
  }

  pieChart.value = echarts.init(chartDom)
  
  const pieData = assetList.map(item => ({
    name: item.status,
    value: item.count
  }))


  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: assetList.map(item => item.status)
    },
    series: [
      {
        name: '资产状态',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter:'{b}: {c} ({d}%)'
        }
      }
    ],
    // 无数据提示
    graphic: assetList.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }
  pieChart.value.setOption(option)
}

// 初始化柱状图
const initStatusBarChart = () => {
  const chartDom = document.getElementById('statusBarChart')
  if (!chartDom) return
  
  // 销毁旧实例，避免内存泄漏
  if (statusBarChart.value) {
    statusBarChart.value.dispose()
  }
  barChart.value = echarts.init(chartDom)
  
  const pieData = assetList.map(item => ({
    name: item.status,
    value: item.count
  }))

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: assetList.map(item => item.status)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        data: pieData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  barChart.value.setOption(option)
}

// 初始化图表
const initCharts = () => {
  initStatusPieChart()
  initStatusBarChart()
}

// 处理窗口大小变化
const handleResize = () => {
  if (pieChart.value) {
    pieChart.value.resize()
  }
  if (barChart.value) {
    barChart.value.resize()
  }
}

// 处理筛选变化
const handleFilterChange = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  console.log('刷新数据，状态:', statusFilter.value, '分类:', categoryFilter.value)
  loadData()
  initCharts()
}

// 格式化金额
const formatMoney = (row, column, cellValue) => {
  return '¥' + cellValue.toLocaleString('zh-CN')
}

// 生命周期 - 挂载后
onMounted(() => {
  loadData()
  initCharts()
  window.addEventListener('resize', handleResize)
})

// 生命周期 - 卸载前
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (pieChart.value) {
    pieChart.value.dispose()
  }
  if (barChart.value) {
    barChart.value.dispose()
  }
})

</script>




<style scoped>
.status-distribution-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 320px;
}

.data-table {
  margin-top: 30px;
}
</style>